# -*- coding: utf-8 -*-
import os

from abc import ABC
from uuid import uuid1

from app.configs import tmp_path
from app.models import db_session
from app.models.model import MetaModel
from app.models.cod import named
from app.views import CommonHandler
from app.models.dao import dxf2db, db2dxf, db2meta, clear_all
from app.models.cod import ValkyrjaException, Error


class DxfHandler(CommonHandler, ABC):
    async def get(self):
        meta_id = self.get_argument("meta_id", None)
        try:
            meta = db2meta(meta_id)
        except ValkyrjaException:
            await self.respose(error=Error.NotMeta)
            return

        code, meta_id = meta['mine_code'], meta['meta_id']
        sign, type, piece = meta['sign'], meta['type'], meta['piece']
        name = named(code, sign, type, piece, meta_id)
        file = tmp_path + name + ".dxf"

        name = meta['name'].encode("utf-8").decode("latin1")
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=' + name)

        if os.path.exists(file):
            with open(file, 'rb') as f:
                content = f.read()
            self.write(content)
            await self.finish()
            return

        db2dxf(file, meta_id)

        with open(file, 'rb') as f:
            content = f.read()
            self.write(content)
        await self.finish()

    async def post(self):
        files = self.request.files.get('file')
        code = self.request.arguments.get('code')
        name = self.request.arguments.get('name')
        sign = self.request.arguments.get('sign')
        type = self.request.arguments.get('type')
        piece = self.request.arguments.get('piece')
        version = self.request.arguments.get('version')
        uuid = self.request.arguments.get('uuid')
        if uuid is not None:
            clear_all(meta_id=uuid[0].decode('utf-8'))

        code = code[0].decode('utf-8') if code else None
        name = name[0].decode('utf-8') if name else None
        sign = sign[0].decode('utf-8') if sign else None
        type = type[0].decode('utf-8') if type else None
        piece = piece[0].decode('utf-8') if piece else None
        version = version[0].decode('utf-8') if version else None
        uuid = uuid[0].decode('utf-8') if uuid else str(uuid1())

        # 查找当前图件时候已经存在
        minor_ver, metas = 1, db_session().query(MetaModel).filter_by(
            mine_code=code, sign=sign, type=type, piece=piece, major_ver=version
        ).order_by(MetaModel.minor_ver.desc()).all()
        if len(metas) > 0:
            minor_ver = metas[0].minor_ver + 1

        if files is not None and len(files) > 0:
            if os.path.exists(tmp_path) is False:
                os.mkdir(tmp_path)
            file = tmp_path + named(code, sign, type, piece, uuid) + '.dxf'
            with open(file, "wb") as fw:
                fw.write(files[0].body)

            meta = {
                'meta_id': uuid,
                'name': files[0].filename.split('.')[0],
                'mine_code': code,
                'mine_name': name,
                'sign': sign,
                'type': type,
                'piece': piece,
                'major_ver': version,
                'minor_ver': minor_ver,
                'cs': '3857'
            }

            dxf2db(file, meta)

        await self.respose(data={'meta_id': uuid})
